import { ProFormDigit, ProFormText } from '@ant-design/pro-components';
import React from 'react';
import { addItem, delItem, detailItem, getList, updateItem } from '@/services/system/dict';
import { getOptionBtn } from '@/util/table';
import { AUTH_TYPE, MENU_CODES } from '@/options';
import { MSG } from '@/util/msg';
import { Button } from 'antd';
import useAuth from '@/hooks/useAuth';
import usePageVariable from '@/hooks/usePageVariable';
import MyPageContainer from '@/components/MyPageContainer';
import MyScrollTable from '@/components/MyScrollTable';
import MyIcon from '@/components/MyIcon';
import MyForm from '@/components/MyForm';
import useDefaultColumn from '@/hooks/useDefaultColumn';

type DataType = DICT_TYPE.Info;

type Props = {
  changeShow?: (show: boolean, data?: DataType) => void;
  currentRow: DataType;
  isShow: boolean;
  setIsShow?: React.Dispatch<React.SetStateAction<boolean>>;
};

const TableList: React.FC<Props> = (props) => {
  const { listAuth, insertAuth, updateAuth, detailAuth, delAuth } = useAuth(MENU_CODES.DICT);
  const defaultColumn = useDefaultColumn();
  const {
    formModel,
    setFormModel,
    formType,
    actionRef,
    formRef,
    currentRow,
    finishMsg,
    columns,
    changeForm,
    getFormTitle,
    delMsgOpen,
    setDelMsgOpen,
  } = usePageVariable<DataType>([
    defaultColumn.index,
    defaultColumn.title,
    {
      title: '标识',
      dataIndex: 'code',
      // hideInTable: props.currentRow.parentId === '0',
      hideInSearch: props.currentRow.parentId !== '0',
    },
    {
      title: '值',
      dataIndex: 'value',
      hideInSearch: true,
    },
    defaultColumn.seq,
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        updateAuth && getOptionBtn(AUTH_TYPE.UPDATE, () => changeForm(record, '1')),
        detailAuth && getOptionBtn(AUTH_TYPE.DETAIL, () => changeForm(record, '2')),
        delAuth && getOptionBtn(AUTH_TYPE.DELETE, () => changeForm(record, '3')),
      ],
    },
  ]);
  const delCall = () =>
    finishMsg(async () => {
      const ret = await delItem(currentRow!.id);
      setDelMsgOpen(false);
      if (ret.success) actionRef.current?.reload();
    });

  const onFinish = async (value: DataType) => {
    if (formType === '2') {
      setFormModel(false);
      return;
    }
    await finishMsg(async () => {
      await (formType === '1'
        ? updateItem({
            ...value,
            id: currentRow!.id,
            code: props.currentRow.code || value.value,
          })
        : addItem({
            ...value,
            parentId: props.currentRow.id,
            code: props.currentRow.code || value.value,
          }));
      setFormModel(false);
      actionRef.current?.reload();
      formRef.current?.resetFields();
    });
  };
  return (
    <MyPageContainer
      content={`${MSG.DELETE_TIP}${
        props.currentRow.parentId === '0' ? '该操作会删除该字典下的所有字典项!!!' : ''
      }`}
      modelOk={delCall}
      delMsgOpen={delMsgOpen}
      modelCancel={setDelMsgOpen}
    >
      <MyScrollTable<DataType, PageParams>
        actionRef={actionRef}
        className="myTable"
        request={(params, sort, filter) =>
          getList({ parentId: props.currentRow?.parentId || undefined, ...params }, sort, filter)
        }
        columns={columns}
        clickAdd={changeForm}
        isAdd={insertAuth}
        toolBarRender={() => [
          props.currentRow.parentId !== '0' && (
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                props.changeShow?.(true);
              }}
            >
              <MyIcon name="ExportOutlined" /> 返回
            </Button>
          ),
        ]}
        onRow={(record) => {
          return {
            onClick: () => {
              if (props.isShow && listAuth)
                props.changeShow?.(false, {
                  ...record,
                  parentId: record.id,
                });
            },
          };
        }}
      />
      <MyForm
        formRef={formRef}
        title={getFormTitle()}
        open={formModel}
        request={currentRow?.id ? () => detailItem(currentRow.id) : undefined}
        onOpenChange={setFormModel}
        onFinish={onFinish}
        readonly={formType === '2'}
      >
        <ProFormText
          label="名称"
          name="title"
          fieldProps={{
            maxLength: 30,
            showCount: true,
          }}
          rules={[
            {
              required: true,
              message: '名称为必填项',
            },
          ]}
        />
        <ProFormText
          label="值"
          name="value"
          fieldProps={{
            maxLength: 30,
            showCount: true,
          }}
          rules={[
            {
              required: true,
              message: '值为必填项',
            },
          ]}
        />
        <ProFormDigit label="排序" name="seq" />
      </MyForm>
    </MyPageContainer>
  );
};

export default TableList;
